package com.ruibang.glass.equipment.service.impl.device;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruibang.glass.common.constants.RedisKey;
import com.ruibang.glass.equipment.domain.req.WareHouseManagementReq;
import com.ruibang.glass.equipment.dto.SelectDTO;
import com.ruibang.glass.equipment.entity.device.WareHouseManagement;
import com.ruibang.glass.equipment.mapper.device.WareHouseManagementMapper;
import com.ruibang.glass.equipment.service.WareHouseManagementService;
import com.teaming.cloud.framework2.autoconfigure.redis.RedisSingleService;
import com.teaming.cloud.framework2.common.model.ResultBody;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;


@Slf4j
@Service
public class WareHouseManagementServiceImpl extends ServiceImpl<WareHouseManagementMapper, WareHouseManagement> implements WareHouseManagementService {

    @Autowired
    private RedisSingleService redisService;

    /**
     * 仓库管理
     * @param managementReq
     * @return
     */
    @Override
    public IPage<WareHouseManagement> queryPage(WareHouseManagementReq managementReq) {
        IPage<WareHouseManagement> page = baseMapper.queryPage(new Page<>(managementReq.getPageNo(), managementReq.getPageSize()), managementReq);
        if(page!=null&& CollectionUtils.isNotEmpty(page.getRecords())){
            Map<Object,Object> userMap = redisService.hmget(RedisKey.USER_GROUP_TYPE);
            for (WareHouseManagement record : page.getRecords()) {
                Object userName = userMap.get(record.getAdminId());
                if(userName!=null){
                    record.setAdminName(userName.toString());
                }
            }
        }
        return page;
    }

    @Override
    public ResultBody updateOrAddById(WareHouseManagement wareHouseManagement) {
        if (StringUtils.isBlank(wareHouseManagement.getId())) {
            Integer number = baseMapper.getMaxNumber();
            if(number==null){
                number = 0;
            }else{
                number++;
            }
            wareHouseManagement.setNumber(number);
            baseMapper.insert(wareHouseManagement);
            return ResultBody.success();
        }
        baseMapper.updateById(wareHouseManagement);
        return ResultBody.success();
    }

    @Override
    public List<SelectDTO> getWareList() {
        return baseMapper.getWareList();
    }
}
